import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  AssetPoolGetAssetPoolName,
  AssetPoolCreate,
  GetFinancingAssetSecuritizationNameTheProcurementItem,
  GetDictionaryByDictCode,
  AssetPoolGetAllByPagedAndSort,
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useFincilaAssetPools() {
  const route = useRoute()
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const RefEntryPlatform = ref()
  const projectList = ref([])
  const securitiesList = ref([])
  const creditRatingList = ref([])
  const showDetail = ref(false)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "资产证券化项目名称",
      prop: "assetSecuritizationName",
    },
    {
      label: "基础资产类型",
      prop: "underlyingAssetType",
    },
    {
      label: "证券承销商",
      prop: "securitiesUnderwriter",
    },
    {
      label: "信用评级机构",
      prop: "creditRatingAgency",
    },
    {
      label: "操作",
      prop: "operation",
      width: 180,
      slot: "operation"
    },
  ];
  const EntryPlatform = reactive({
    projectName: '',
    supplerName: '',
    securities: '',
    creditRating: '',
    money: '',
    leaveDay: '',
    purchaseOrderId: '',
    approver: '',
  })

  const approverList = ref([{ dictName: '深圳交易所', dictId: 'sz' }, { dictName: '上海交易所', dictId: 'sh' }])
  // 万亿 长度 14
  const rules: any = {
    projectName: [
      {
        required: true,
        message: '请选择资产证券化项目名称',
        trigger: 'blur',
      }
    ],
    securities: [
      {
        required: true,
        message: '请选择证券承销商',
        trigger: 'blur',
      }
    ],
    creditRating: [
      {
        required: true,
        message: '请选择信用评级机构',
        trigger: 'blur',
      }
    ],
    financingLine: [
      {
        required: true,
        message: '请输入融资金额',
        trigger: 'blur',
      }
    ],
    approver: [
      {
        required: true,
        message: '请选择证券交易所',
        trigger: 'blur',
      }
    ],
  };

  function SubtimEntryPlatform(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        planId: route.query.planId,
        taskId: route.query.taskId,
        assetSecuritizationName: EntryPlatform.projectName,
        underlyingAssetType: "应收账款债权",
        initiator: EntryPlatform.supplerName,
        securitiesUnderwriter: EntryPlatform.securities,
        creditRatingAgency: EntryPlatform.creditRating,
        smallLoanCreditbalance: EntryPlatform.money,
        smallLoanInterestRate: "9.125%",
        termSmallLoan: EntryPlatform.leaveDay,
        purchaseOrderId: EntryPlatform.purchaseOrderId,
        securityName: securitiesList.value.find(item => item.dictId == EntryPlatform.securities).dictName,
        StockExchange: EntryPlatform.approver,
        CreditRatingAgencyName: creditRatingList.value.find(item => item.dictId == EntryPlatform.creditRating).dictName,
      };
      const res = await AssetPoolCreate(data);
      if (res.success) {
        ElMessage.success(res.msg)
        CloseEntryPlatform(row);
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  function CloseEntryPlatform(row: FormInstance | undefined) {
    row.resetFields();
    DialogVisible.value = false;
    showDetail.value = false
  }

  async function getList() {
    const res = await AssetPoolGetAllByPagedAndSort({
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
    });
    if (res.success) {
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }


  onMounted(async () => {
    getList()
    let data = qs.stringify({
      dictCode: 'SecuritiesUnderwriter'
    })
    const res = await GetDictionaryByDictCode(data)
    if (res.success) {
      securitiesList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    let data1 = qs.stringify({
      dictCode: 'CreditRatingAgency'
    })
    const res1 = await GetDictionaryByDictCode(data1)
    if (res1.success) {
      creditRatingList.value = res1.data
    } else {
      ElMessage.error(res1.msg)
    }
    const data2 = qs.stringify({
      taskId: route.query.taskId,
      planId: route.query.planId
    })
    const res2 = await GetFinancingAssetSecuritizationNameTheProcurementItem(data2)
    if (res2.success) {
      res2.data.forEach(item => item.purchaseName = item.purchaseName.split(";").join(",").replace(/^,/, "") + '应收账款债权资产专项计划')
      projectList.value = res2.data
    } else {
      ElMessage.error(res2.msg)
    }
  })

  function handleSizeChange() {
    getList()
  }
  function handleCurrentChange() {
    getList()
  }

  function changeProject(row) {
    EntryPlatform.leaveDay = row.averageNumberDaysRemaining
    EntryPlatform.money = row.accountReceivableAmount
    EntryPlatform.supplerName = row.supplyName
    EntryPlatform.purchaseOrderId = row.purchaseOrderId
  }

  function check(row) {
    showDetail.value = true;
    DialogVisible.value = true;
    nextTick(() => {
      EntryPlatform.projectName = row.assetSecuritizationName
      EntryPlatform.leaveDay = row.termSmallLoan
      EntryPlatform.money = row.smallLoanCreditbalance
      EntryPlatform.supplerName = row.initiator
      EntryPlatform.creditRating = row.creditRatingAgency
      EntryPlatform.securities = row.securitiesUnderwriterId
      EntryPlatform.approver = row.stockExchange
    })
  }
  return {
    rules,
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    DialogVisible,
    EntryPlatform,
    RefEntryPlatform,
    CloseEntryPlatform,
    SubtimEntryPlatform,
    projectList,
    securitiesList,
    creditRatingList,
    changeProject,
    check,
    showDetail,
    approverList
  }
}
